<template>
	<!-- <u-navbar title="查询分页列表" bgColor="#FBFBFF" :autoBack="true" :style="{ paddingTop: safeAreaInsets?.top + 'px' }">
	</u-navbar> -->
	<view class="baseForm">
		<u--form labelPosition="left" :model="umodel" :rules="rules" ref="uForm" class="form" labelWidth="160rpx"
			errorType="toast">
			<u-form-item label="工厂">
				<u--input v-model="umodel.plantName" placeholder="请填写工厂" inputAlign="right" clearable :disabled="true"
					border="none"></u--input>
			</u-form-item>
			<u-form-item label="工作中心">
				<u--input v-model="umodel.workCenterCodeName" placeholder="请填写工作中心" inputAlign="right" clearable
					:disabled="true" border="none"></u--input>
			</u-form-item>
			<u-form-item label="班组">
				<u--input v-model="umodel.crewName" placeholder="请填写班组" inputAlign="right" clearable :disabled="true"
					border="none"></u--input>
			</u-form-item>
			<!--<u-form-item label="日期" @click="openTimeSelect">
				<u-datetime-picker hasInput :show="show" v-model="umodel.createDateTime" mode="date"
					@confirm="dateChange"></u-datetime-picker>
			</u-form-item> -->
			<u-form-item label="日期" @click="openTimeSelect">
				{{umodel.createDate}}
				<u--input v-model="umodel.createDate" border="none" disabled disabledColor="#ffffff" v-if="false"
					placeholder="请选择时间"></u--input>
				<u-datetime-picker :show="show" v-model="umodel.createDateTime" mode="date" @cancel="show = false"
					@confirm="dateChange"></u-datetime-picker>
			</u-form-item>
			<u-form-item label="班次" prop="shiftName">
				<u--input v-model="umodel.shiftName" inputAlign="right" placeholder="请选择班次" clearable border="none"
					@click="shiftShow = true" :disabled="true"></u--input>
			</u-form-item>
			<u-form-item label="姓名" prop="memberName">
				<u--input v-model="umodel.memberName" inputAlign="right" placeholder="请填写姓名" clearable border="none"
					@click="memberNameShow = true" :disabled="true"></u--input>
			</u-form-item>
			<u-form-item label="报工状态">
				<u--input v-model="umodel.reportStateName" placeholder="" inputAlign="right" clearable :disabled="true"
					border="none"></u--input>
			</u-form-item>
		</u--form>
		<!-- 卡片显示 -->
		<view class="container">
			<text class="list-title">列表信息({{ total }})</text>
			<button class="uni-btn" size="mini" plain type="primary" @click="detail()">填报</button>
			<button class="uni-btn" size="mini" plain type="primary" @click="submitAndDelete()">提交</button>
		</view>
		<view class="activeHeight">
			<!-- 列表 -->
			<u-list class="list" v-if="total" lowerThreshold="100px">
				<u-list-item v-for="(item, index) in materialReturnList" :key="item.id"
					@click="updatePlan(item, index)">
					<view class="card">
						<view class="right">
							<view class="title1">
								报工类型：{{ item?.unscheduledReportTypeName || '' }}
							</view>
							<view class="des">开始时间：{{ item?.startTime || '' }}</view>
							<view class="des">完工时间：{{ item?.completeTime || '' }}</view>
							<view class="des">中断时长/分：{{ item?.totalTime || '0' }}</view>
							<text class="des"
								style="width: 100%;white-space: wrap; word-break: break-all;">报工说明：{{ item?.unscheduledReportContent || '' }}</text>
						</view>
						<!-- <view class="left">
							<view class="title">
								<button class="uni-btn" size="mini" plain type="primary"
									>编辑</button>
							</view>
						</view> -->
					</view>
				</u-list-item>
			</u-list>
			<!-- 空数据 -->
			<view v-else>
				<u-empty mode="list" icon="http://cdn.uviewui.com/uview/empty/list.png"></u-empty>
			</view>
		</view>
		<u-modal :show="showImport" ref="uModal" :content="`请确认是否对当非生产报工记录进行提交处理？`" :confirmText="selectState"
			showCancelButton @cancel="cancelImport" @confirm="confirmImport"></u-modal>
		<u-picker :show="shiftShow" :columns="shiftList" @cancel="shiftShow = false" @confirm="handelshift"
			keyName="shiftName"></u-picker>
		<u-picker :show="memberNameShow" :columns="memberNameList" @cancel="memberNameShow = false"
			@confirm="handelMemberName" keyName="memberName"></u-picker>
	</view>
	<u-back-top :scroll-top="scrollTop" top="200" mode="squery"></u-back-top>
</template>

<script lang="ts" setup>
	import { computed, reactive, ref } from 'vue';
	import { onPageScroll, onPullDownRefresh, onShow } from '@dcloudio/uni-app';
	import { http } from '@/utils/http';
	import { useUserStore } from '../../../stores/useUserStore';
	import { useProduceStore } from '../../../stores/useProduceStore';
	import { useDictionaryStore } from '../../../stores/useDictionaryStore';
	// loginWorkInfo
	const loginWorkInfo = computed(() => JSON.parse(useUserStore().loginWorkInfo));
	console.log("loginWorkInfo", loginWorkInfo.value)
	let crewMemberList = computed(() => JSON.parse(useProduceStore().crewMemberList));
	console.log('工厂', crewMemberList.value)

	// 监听页面到顶部距离
	const scrollTop = ref(0)
	onPageScroll((e) => {
		scrollTop.value = e.scrollTop
	})

	onShow(async () => {
		getUnscheduledList()
		useProduceStore().setPlanAddDetailList([]);
		getShiftList()
		getMemberList()
	})
	const umodel = ref({
		id: "",
		unscheduledReportCode: "",
		unscheduledReportType: "",
		unscheduledReportContent: "",
		organizationId: "",
		organizationCode: "",
		plantId: "",
		plantCode: "",
		plantName: "",
		producePlanId: "",
		producePlanCode: "",
		produceOrderId: "",
		produceOrderCode: "",
		workCenterId: "",
		workCenterCode: "",
		workCenterName: "",
		workCenterCodeName: "",
		createDateTime: Date.now(),
		createDate: "",
		crewId: "",
		crewName: "",
		shiftId: "",
		shiftCode: "",
		shiftName: "",
		startTime: 0,
		completeTime: 0,
		totalTime: 0,
		totalCost: 0,
		reportQuantity: 0,
		reportState: "",
		reportStateName: "新建",
		memberId: "",
		memberName: "",
		detailsPlan: [],
		detailsMember: [],

	});
	//工厂信息
	umodel.value.plantId = crewMemberList.value[0].plantId
	umodel.value.plantCode = crewMemberList.value[0].plantCode
	umodel.value.plantName = crewMemberList.value[0].plantName
	umodel.value.workCenterId = loginWorkInfo.value.workCenterId
	umodel.value.workCenterCode = loginWorkInfo.value.workCenterCode
	umodel.value.workCenterName = loginWorkInfo.value.workCenterName
	umodel.value.workCenterCodeName = loginWorkInfo.value.workCenterCode + '-' + loginWorkInfo.value.workCenterName 
	umodel.value.crewId = loginWorkInfo.value.crewId
	umodel.value.crewName = loginWorkInfo.value.crewName
	//下拉列表
	const shiftShow = ref(false);
	const memberNameShow = ref(false);
	const shiftList = reactive([]);
	const memberNameList = reactive([]);
	let member = ref({
		memberId: "",
		memberName: "",
	})
	const getShiftList = async () => {
		if (!loginWorkInfo.value.workCenterId) {
			return;
		}
		shiftList[0] = []
		if (!umodel.value.createDate) {
			const date = new Date(Date.now());
			umodel.value.createDate = formatDate(date)
		}
		const { data } = await http({
			method: "POST",
			url: `/mes/mesunscheduledreport/getScheduleDetail`,
			data: {
				createDate: umodel.value.createDate,
				workCenterId: loginWorkInfo.value.workCenterId
			}
		});
		shiftList[0] = data
	};
	const getMemberList = async () => {
		if (!loginWorkInfo.value.workCenterId) {
			uni.$u.toast('请前往加工单扫描工作中心!', 3000);
			uni.switchTab({
				url: '/pages/index/index'
			})
			return;
		}
		const { data } = await http({
			method: "POST",
			url: `/mes/mescrew/getCrewMembers`,
			data: {
				// workCenterId: loginWorkInfo.value.workCenterId,
				id: loginWorkInfo.value.crewId,
			}
		});
		memberNameList[0] = data
	};
	const handelshift = (e) => {
		let item = e.value[0]
		umodel.value.shiftId = item.id
		umodel.value.shiftCode = item.shiftCode
		umodel.value.shiftName = item.shiftName
		getUnscheduledList()
		shiftShow.value = false;
	};
	const handelMemberName = (e) => {
		let item = e.value[0]
		// console.log(item.memberId)
		umodel.value.memberId = item.memberId
		umodel.value.memberName = item.memberName
		member.value.memberId = item.memberId
		member.value.memberName = item.memberName
		getUnscheduledList()
		memberNameShow.value = false;
	};
	const show = ref(false);

	// 请求列表参数定义
	const materialReturnList = ref(); // 缺货要货集合
	const current = ref(0); // 当前页
	const totalPage = ref(0); //累计分页
	const total = ref(0); // 累计条数

	// 初始化参数
	function reset() {
		current.value = 0;
		materialReturnList.value = [];
		total.value = 0;
		totalPage.value = 0;
	}
	onPullDownRefresh(() => {
		current.value = 0;		//分页第一页
		materialReturnList.value = [];	//数据清空
		getUnscheduledList('refresh');	//数据请求
	})


	async function getUnscheduledList(type ?: string) {
		if (!umodel.value.shiftId || !umodel.value.memberId) {
			return
		}
		umodel.value.reportState = ""
		umodel.value.reportStateName = "新建"
		try {
			const result = await http({
				method: 'POST',
				url: '/mes/mesunscheduledreport/queryByList',
				data: umodel.value
			});

			if (result.data.length > 0) {
				materialReturnList.value = result.data[0].detailsPlan;
				umodel.value.id = result.data[0].id
				total.value = result.data[0].detailsPlan.length;
				materialReturnList.value.forEach(item => {
					item.unscheduledReportTypeName = useDictionaryStore().filterDictName("ReportType", item.unscheduledReportType)
				});
				umodel.value.reportState = result.data[0].reportState
				umodel.value.reportStateName = useDictionaryStore().filterDictName("ReportState", result.data[0].reportState)
			} else {
				materialReturnList.value = []
				total.value = 0
				umodel.value.id = ""
				umodel.value.reportState = ""
				umodel.value.reportStateName = "新建"
			}
			type === 'refresh' && uni.stopPullDownRefresh();
		} catch (e) {
			console.log(e);
		}
	}
	// 选择订单
	const selectOrder = ref({});
	const selectIndex = ref();
	const selectState = ref()
	const showImport = ref(false);
	function submitAndDelete() {
		if (!umodel.value.shiftId || !umodel.value.memberId) {
			uni.$u.toast('请选择班次或姓名');
			return
		}
		if (materialReturnList.value.length <= 0) {
			uni.$u.toast('填报后提交！');
		} else {
			if (umodel.value.reportState == "1" || umodel.value.reportState == "2") {
				uni.$u.toast('状态为已提交或同意，无法再次提交！');
				return
			}
			showImport.value = true;
		}
	}
	// 取消选择订单
	function cancelImport() {
		showImport.value = false;
		selectOrder.value = {};
		selectIndex.value = null;
		selectState.value = "";
	}
	// 提交
	async function confirmImport() {
		const res = await http({
			method: 'POST',
			url: '/mes/mesunscheduledreport/approval',
			data: {
				reportState: 1,
				ids: [umodel.value.id],
			}
		});
		if (res.code == "200") {
			uni.showToast({
				title: '提交成功'
			});
			uni.navigateBack({
				delta: 1, //返回层数，2则上上页
			})
		}

		showImport.value = false;
		getUnscheduledList()
	}
	//编辑
	function updatePlan(row, index) {
		row.reportState = umodel.value.reportState
		if (!umodel.value.reportState) {
			row.reportState = "0"
		}
		console.log("row", row)
		uni.navigateTo({
			url: `/pages/produce/unscheduledReport/planAddDetail?result=${JSON.stringify(row)}`
		});
	}
	//填报
	function detail() {
		if (!umodel.value.shiftId || !umodel.value.memberId) {
			uni.$u.toast('请选择班次或姓名');
			return
		}
		if (umodel.value.reportState == "1" || umodel.value.reportState == "2") {
			uni.$u.toast('状态为已提交或同意，无法填报！');
			return
		}
		if (!umodel.value.reportState) {
			umodel.value.reportState = "0"
		}
		umodel.value.detailsMember = []
		umodel.value.detailsMember.push(member.value)
		uni.navigateTo({
			url: `/pages/produce/unscheduledReport/planAddDetail?result=${JSON.stringify(umodel.value)}`
		});
	}

	// 表单规则定义
	const rules = ref({
		shiftName: [
			{
				required: true,
				type: "string",
				message: "请选班次",
				trigger: ["blur", "change"],
			},
		],
		memberName: [
			{
				required: true,
				type: "string",
				message: "请选择人员",
				trigger: ["blur", "change"],
			},
		],
	});

	//日期变化触发
	function dateChange(e) {
		if (e) {
			const date = new Date(e.value);
			umodel.value.createDate = formatDate(date);
			umodel.value.createDateTime = e.value
			show.value = false;
			//日期变更时清除班次信息与列表数据
			umodel.value.shiftId = ""
			umodel.value.shiftName = ""
			materialReturnList.value = []
			total.value = 0
			getShiftList()
			getUnscheduledList()
		}
	}
	function formatDate(date) {
		const year = date.getFullYear();
		const month = (date.getMonth() + 1).toString().padStart(2, '0');
		const day = date.getDate().toString().padStart(2, '0');
		return `${year}-${month}-${day}`;
	}
	function openTimeSelect() {
		show.value = true;
		uni.hideKeyboard();
	}
</script>

<style lang="scss" scoped>
	.baseForm {
		:deep(.uni-scroll-view) {
			overflow: inherit;
		}

		.u-form {
			padding: $uni-page-padding;

			:deep(.u-form-item__body) {
				padding: 5px 0;
			}

			.u-input {
				border: 1px solid $uni-input-border-color;
			}

			.scan-bar {
				margin-top: 5px;
				display: flex;
				flex: 1;
			}
		}

		.u-line {
			padding: 10px 0;
		}

		:deep(.u-form-item__body__right__content__slot) {
			flex-direction: row-reverse;
		}

		.search {
			display: flex;

			.custom-style {
				// width: 120px;
				margin: 10px 5px 5px;
				height: 36px;
				border-radius: 8px;

				&:nth-child(1) {
					flex: 1
				}

				&:nth-child(2) {
					flex: 3
				}
			}
		}

		.list-title {
			flex: 0.8;
			line-height: 40px;
			font-size: 14px;
			color: rgba(0, 0, 0, 0.4);
			margin-left: 15px;
		}

		.list {
			.card {
				margin: $uni-page-padding;
				margin-top: 5px;
				margin-bottom: 5px;
				border-radius: 7px;
				display: flex;
				align-items: center;
				padding: 1px 10px 0px 10px;
				transition: all 300ms ease;
				box-shadow: 0 1px 5px rgba(19, 11, 236, 0.13);
				background-color: #fff;
				display: flex;
				align-items: flex-start;

				.left {
					// flex: 1;
					// margin-left: -53px;
					flex-basis: calc(20%);
				}

				.title {
					font-size: 14px;
					line-height: 40px;
					height: 37px;
					margin-top: 0px;

					color: #101010;
					border-bottom: 1px solid #E5EBFF;
				}

				.title1 {
					font-size: 12px;
					line-height: 40px;
					height: 37px;
					margin-top: 0px;
					width: 265px;
					color: #101010;
					border-bottom: 1px solid #E5EBFF;
					font-weight: 700;

				}

				.uni-btn {
					float: right;
					font-size: 12px;
					height: 24px;
					line-height: 24px;
					padding: 0 15px;
					margin-top: 7px;
					font-weight: 400;
				}

				.des {
					font-size: 12px;
					line-height: 20px;
					height: 20px;
					margin-top: 5px;
					margin-bottom: 5px;
				}

				.des {
					font-size: 12px;
					line-height: 20px;
					height: 20px;
					margin-top: 5px;
					margin-bottom: 5px;
				}

				.right {
					// flex: 3;
					flex-basis: calc(80%);
				}
			}
		}

		.container {
			display: flex;
			/* 使用Flexbox布局 */
			align-items: center;
			/* 垂直居中 */
			margin-right: 15px;
			// justify-content: center; /* 水平居中 */
			// height: 200px; /* 容器高度 */
			// border: 1px solid #000; /* 边框，仅为了演示 */
		}
	}
</style>